package com.mmall.demo2.common.serialize;

import org.apache.commons.lang3.ObjectUtils;

import java.io.*;

/**
 * @Author: jiaru
 * @Description: 对象映射类：用于将 java 对象转换成指定数据类型
 * @Date: Created on 2018/10/31
 * @Modify:
 */
public class ObjectMapper extends ObjectUtils {

    // 编码格式
    private static final String CHARSET = "UTF-8";


    /**
     * 对象转换成 byte[] 类型
     * @param obj
     * @return
     */
    public static byte[] toBytes(Object obj) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            if (obj != null){
                baos = new ByteArrayOutputStream();
                oos = new ObjectOutputStream(baos);
                oos.writeObject(obj);
                return baos.toByteArray();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 转换为字节数组
     * @param str string数组
     * @return
     */
    public static byte[] getBytes(String str){
        if (str != null){
            try {
                return str.getBytes(CHARSET);
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        }else{
            return null;
        }
    }

    /**
     * byte[] 转换Object
     * @param bytes
     * @return
     */
    public static Object toObject(byte[] bytes) {
        ByteArrayInputStream bais = null;
        try {
            if (bytes != null && bytes.length > 0){
                bais = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = new ObjectInputStream(bais);
                return ois.readObject();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
